from django.shortcuts import render
from rest_framework.views import APIView
from django import http
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from libs.yuntongxun.sms import CCP
from rest_framework import status
from . import serializers

import random


# 保存,返回圖片驗證碼
class ImageCodeView(APIView):
    def get(self,request,image_code_id):
        # 生成圖片驗證碼
        text,image_data = captcha.generate_captcha()
        print(text)

        # 保存驗證碼的值
        redis_conn = get_redis_connection("code")
        redis_conn.setex("image_code_%s"%image_code_id,300,text)

        # 返回響應
        response = http.HttpResponse(image_data)
        response["Content-Type"] = "image/png"
        return response


# 短信驗證碼接口
class SmsCodeView(GenericAPIView):
    serializer_class = serializers.SmsCodeSerializer

    def get(self,request,mobile):
        # 獲取參數
        dict_data = request.query_params

        # 創建序列化器,校驗
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        # 判斷是否頻繁發送短信
        redis_conn = get_redis_connection("code")
        send_flag = redis_conn.get("send_flag_%s"%mobile)
        if send_flag:
            return Response({"errmsg":"短信頻繁發送"},status=status.HTTP_400_BAD_REQUEST)

        # 發送短信
        sms_code = random.randint(0,99999)
        print(sms_code)

        # 使用celery發送短信
        # from celery_tasks.sms.tasks import send_sms_code
        # send_sms_code.delay(mobile,sms_code)

        # result = CCP().send_template_sms(mobile,[sms_code,5],1)
        # if result == -1:
        #     return http.HttpResponseBadRequest("發送失敗")

        # 短信入庫

        redis_conn.setex("sms_code_%s"%mobile,300,sms_code)
        redis_conn.setex("send_flag_%s"%mobile,60,True)

        # 返回響應
        return Response(status=status.HTTP_200_OK)


